var fileindex = 0;
var fileurl = new Array();
var filecount = 0;
$(function() { 
	bindUploadXsb('xsb0',fileindex);
	fileindex++;
	filecount++;
}); 

//判断字符串是否为空
function isEmpty(strVal) {
    if (strVal == '' || strVal == null || strVal == undefined) {
        return true;
    } else {
        return false;
    }
}

function submitShopInfo(){
	var shopList = new Array();
	var shopFilelist = new Array();
	var shopNameList = new Array();
	var shopSessionList = new Array();
	var shopWwmList = new Array();
	for(var i = 0; i < fileurl.length; i++){
		var str = fileurl[i].toString();
		var index = str.split("#")[0];
		var furl = str.split("#")[1];
		var username = $("#username_"+index).val();
		var wwm = $("#wwm_"+index).val();
		var session = $("#session_"+index).val();
		if(isEmpty(username) || isEmpty(wwm) || isEmpty(session)){
			continue;
		}
		shopList[shopList.length] = index;
		shopFilelist[shopFilelist.length] = furl;
		shopNameList[shopNameList.length] = username;
		shopSessionList[shopSessionList.length] = session;
		shopWwmList[shopWwmList.length] = wwm;
	}
	
	if(shopList.length < 1){
		zeroModal.alert({
	    	content: "店铺信息不能为空,请完善",
            contentDetail: '谢谢您的配合~'
	    });
		return;
	}

	//检查重复度
	for(var i = 0; i < shopNameList.length; i++){
		for(var j = i+1; j < shopNameList.length; j++){
			if(shopNameList[i] == shopNameList[j]){
				zeroModal.alert({
			    	content: "店铺名\""+shopNameList[j]+"\"重名啦~,请确认下",
		            contentDetail: '谢谢您的配合~'
			    });
				return;
			}
			if(shopWwmList[i] == shopWwmList[j]){
				zeroModal.alert({
			    	content: "旺旺名\""+shopWwmList[j]+"\"重名啦~,请确认下",
		            contentDetail: '谢谢您的配合~'
			    });
				return;
			}
		}
	}
	
	//上传信息
	zeroModal.loading(3);
	var errorFiles = "";
	var successFiles = "";
	var errInfo = "";
	var silist = new Array();
	for(var i = 0; i < shopNameList.length; i++){
		var pdata = {"shopname":shopNameList[i],"wwm":shopWwmList[i],"session":shopSessionList[i],"url":shopFilelist[i]};
		$.ajax({
			url: "dshopinfo",
			data: JSON.stringify(pdata),
			contentType: "application/json",
			dataType: 'json',
			type: "POST",
			async: false,
			success: function (result) { 
				if(result.status == 200){
					successFiles += shopNameList[i]+",";
					silist[silist.length] = shopList[i];
				}else{
					if(shopNameList.length == 1){
						errInfo = result.data;
					}
					errorFiles += shopNameList[i]+",";
				}
	        }
		});
	}
	
	if (successFiles.length > 0) {
		successFiles = successFiles.substring(0, successFiles.length - 1);
		if (errorFiles.length > 0) {
			zeroModal.alert({
				content : "成功提交\"" + successFiles + "\"家店铺信息",
				contentDetail : '还有部分店铺信息提交失败，请确认后重试~',
				okFn : function() {
					for (var i = 0; i < silist.length; i++) {
						deleteShop(silist[i]);
					}
					zeroModal.closeAll();//关闭所有提示框
				}
			});
		} else {
			zeroModal.success({
				content : "成功提交\"" + successFiles + "\"家店铺信息",
				okFn : function() {
					for (var i = 0; i < silist.length; i++) {
						deleteShop(silist[i]);
					}
					zeroModal.closeAll();//关闭所有提示框
					window.location = "shopinfo";
				}
			});
		}
	}else{
		if(shopNameList.length == 1){
			zeroModal.error({
				content:errInfo,
				okFn : function() {
					zeroModal.closeAll();//关闭所有提示框
				},
				onClosed : function() {
					zeroModal.closeAll();//关闭所有提示框
				}
			});
		}else{
			zeroModal.error({
				content:"店铺信息有误，请确认后再重试",
				okFn : function() {
					zeroModal.closeAll();//关闭所有提示框
				},
				onClosed : function() {
					zeroModal.closeAll();//关闭所有提示框
				}
			});
		}
	}
}

function deleteAccount(guid){
	var pdata = {"guid":guid};
	$.ajax({
		url: "../account/delete",
		data: JSON.stringify(pdata),
		contentType: "application/json",
		dataType: 'json',
		type: "POST",
		success: function (result) { 
			if(result.status == 200){
				$("#"+guid+"_tr").remove();
			}else{
				zeroModal.error(result.data);
			}
        }
	});
}

function reSelectFiles(id,index){
	console.log(id,index);
	removeFile(index);
	var str = "<input type='file' name='"+id+"_upload'  id='"+id+"_upload' />";
	
	$("#"+id).html(str);
	bindUploadXsb(id,index);
    $("#"+id+"_uploader").html("");
}

function addShop(){
	if(fileurl.length < filecount){
		zeroModal.alert({
	    	content: "要先完善已有店铺，才能再添加奥~",
            contentDetail: '谢谢您的配合~'
	    });
		return;
	}
	for(var i = 0; i < fileurl.length; i++){
		var str = fileurl[i].toString();
		var index = str.split("#")[0];
		var username = $("#username_"+index).val();
		var wwm = $("#wwm_"+index).val();
		var session = $("#session_"+index).val();
		if(isEmpty(username) || isEmpty(wwm) || isEmpty(session)){
			zeroModal.alert({
		    	content: "要先完善已有店铺，才能再添加",
	            contentDetail: '谢谢您的配合~'
		    });
			return;
		}
	}
	
	var str = "<div id='shop_"+fileindex+"' class='shopInfo'>"
			+"<div class='center-div'><label class='basic-label-ex'>店铺名称</label>"
			+"<input id='username_"+fileindex+"' type='text' class='input-center-wex' placeholder='请输入店铺名称' />" 
			+" <a href='javascript:deleteShop("+fileindex+")' style='font-size:22px;color:rgb(241,49,49)'><span class='glyphicon glyphicon-remove'></span></a></div>"
			+"<div class='center-div'><label class='basic-label-ex'>主店铺旺旺名</label>"
			+"<input id='wwm_"+fileindex+"' type='text' class='input-center-wex' placeholder='请输入主店铺旺旺名' />"
			+" <a href='#'><img src='../images/c_img/ques.png' style='width: 22px;height: 22px;margin-top: -3px;'></a></div>"
			+"<div class='center-div'><label class='basic-label-ex'>授权码</label>"
			+"<input id='session_"+fileindex+"' type='text' class='input-center-wex' placeholder='请输入授权码' />"
			+" <a href='#'><img src='../images/c_img/ques.png' style='width: 22px;height: 22px;margin-top: -3px;'></a></div>"
			+"<div class='center-div'><label class='basic-label-ex'>销售表(可选)</label>"
			+"<div id='xsb"+fileindex+"' style='display:inline-block'><input type='file' name='xsb"+fileindex+"_upload' id='xsb"+fileindex+"_upload' /></div>"
			+" <a href='#'><img src='../images/c_img/ques.png' style='width: 22px;height: 22px;margin-top: -3px;margin-left:14px;margin-right:15px;'></a>"
			+"<div style='display:inline-block' id='xsb"+fileindex+"_uploader'></div></div></div>"
	
	$("#addshopa").before(str);
	bindUploadXsb('xsb'+fileindex,fileindex);
	fileindex++;
	filecount++;
}

function deleteShop(fileindex){
	$("#shop_"+fileindex).remove();
	removeFile(fileindex);
	filecount--;
}

function removeFile(fileindex){
	for(var i = 0; i < fileurl.length; i++){
		var str = fileurl[i];
		if(str.indexOf(fileindex+"#") > -1){
			fileurl.splice(i, 1);
			return;
		}
	}
}

function bindUploadXsb(id,index){
	//swdj
    $("#"+id+"_upload").uploadify(  
            {  
                'auto' : true,  
                'method' : "get",  
                'formData' : {  
                    'folder' : 'file'  
                },  
                'height' : 35,  
                'swf' : '../uploadify/uploadify.swf', // flash  
                'cancelImg': '../uploadify/uploadify-cancel.png', 
                'uploader' : '../upload/upxsb', //  
                'width' : 299,  
                'fileTypeDesc' : '支持多种文件格式',  
                'fileTypeExts' : '.csv;.CSV',  
                'fileSizeLimit' : '1GB',  
                'buttonText' : '点击上传',  
                'uploadLimit' : 1,  
                'successTimeout' : 5,  
                'requeueErrors' : false,  
                'removeTimeout' : 10,  
                'removeCompleted' : false,  
                'queueSizeLimit' : 10,  
                'queueID' : id+'_uploader',  
                'progressData' : 'percentage',  
                'onInit' : function() {  
                },  
                'onUploadSuccess' : function(file, data, response) { 
                	console.log(index);
                	fileurl[fileurl.length] = index+"#"+data;
                	$("#"+id).html("<span style='color:rgb(249,41,41)'>文件上传成功</span>");
                    $("#"+id+"_uploader .cancel a").remove();
                    $("#"+id+"_uploader .cancel").prepend("<a href=\"javascript:reSelectFiles('"+id+"',"+index+")\">X</a>");
                    console.log(fileurl);
                },
                'onUploadError' : function(file,errorCode,errorMsg,errorString,swfuploadifyQueue) {
                	
                }
            });
}